package scoutobahn.xml.automaton;

import java.util.Collection;
import java.util.LinkedList;

import org.xml.sax.Attributes;

import scoutobahn.xml.LazyOsmItem;
import scoutobahn.xml.OsmRelation;
import scoutobahn.xml.OsmRelationMember;
import scoutobahn.xml.OsmXmlTypes;
/**
 * State for an OsmRelation.
 * @author mark
 *
 */
public class RelationState extends OsmElementState {

    private final Collection<OsmRelationMember> members;
    private long id;
    /**
     * Constructs a new RelationState with the given StateManager and
     * a given OsmItemStreamManager.
     * @param stateManager The StateManager
     * @param listener The OsmItemStreamManager
     */
    public RelationState(final StateManager stateManager,
            final OsmItemStreamManager listener) {
        super(stateManager, "relation", listener);
        this.members = new LinkedList<OsmRelationMember>();
    }

    @Override
    public ParserState startElement(final String nameSpace,
            final String localName,
            final String qName, final Attributes attr) {
        if (localName.equals(super.getElementName())) {
            this.id = Long.parseLong(attr.getValue("id"));
        }
        if (localName.equals("member")) {
            long refId = Long.parseLong(attr.getValue("ref"));
            OsmXmlTypes type =
                    OsmXmlTypes.getTypeFromString(attr.getValue("type"));
            this.members.add(
                    new OsmRelationMember(type,
                            new LazyOsmItem(refId,
                                    super.getItemStreamListener().getProvider(),
                                    type)));
        }
        super.startElement(nameSpace, localName, qName, attr);
        return this;
    }

    @Override
    public ParserState endElement(final String namespace,
            final String localName, final String qName) {
        if (localName.equals(super.getElementName())) {
            super.getItemStreamListener()
            .relationFound(new OsmRelation(this.id,
                    super.getTags(), this.members));
        }
        return super.endElement(namespace, localName, qName);
    }

}
